package com.wzy.netty.core.codec2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 描述  :
 * 创建人:    Wzy
 * 创建时间: 2020-06-11  11:29
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {
    //    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        //读取从客户端发送的sudent
//        StudentPOJO.Student student = (StudentPOJO.Student) msg;
//        System.out.println("客户端发送的数据id= " + student.getId() + "名字: " + student.getName());
//    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyDataInfo.MyMessage myMessage) throws Exception {
        MyDataInfo.MyMessage.DataType dataType = myMessage.getDataType();
        if (dataType == MyDataInfo.MyMessage.DataType.StudentType) {
            MyDataInfo.student student = myMessage.getStudent();
            System.out.println("学生id: " + student.getId() + " ,学生名字: " + student.getName());
        } else if (dataType == MyDataInfo.MyMessage.DataType.workerType) {
            MyDataInfo.worker worker = myMessage.getWorker();
            System.out.println("工人年龄: " + worker.getAge() + " ,工人名字: " + worker.getName());
        } else {
            System.out.println("传输类型错误");
        }
    }

    //服务端返回
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端", CharsetUtil.UTF_8));

    }

    //异常退出
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();
    }


}
